<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title></title>
  </head>
  <body>
    <div id="app">
      <div>提问：<input v-model="question" /></div>
      <div>{{ answer }}</div>
    </div>

    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>

    <script>
      const { createApp, ref, watchEffect } = Vue;

      const app = createApp({
        setup() {
          const question = ref("编程段子?");
          const answer = ref("");

          let timeId;

          // watchEffect 回调会立即执行，不需要指定 immediate: true。
          // 在执行期间，它会自动追踪 question.value 作为依赖（和计算属性类似）
          // 每当 question.value 变化时，回调会再次执行
          watchEffect(() => {
            if (question.value.indexOf("?") > -1) {
              answer.value = "思考中...";

              timeId && clearTimeout(timeId);
              timeId = setTimeout(
                () => (answer.value = `结果为：${question.value}`),
                1000
              );
            }
          });

          return {
            question,
            answer,
          };
        },
      });

      app.mount("#app");
    </script>
  </body>
</html>
